<template>
  <view class="publish-view">
    <!-- 提示信息弹窗 -->
    <uni-popup ref="message" type="message">
      <uni-popup-message :type="data.msgType" :message="data.messageText" :duration="2000"></uni-popup-message>
    </uni-popup>
      <!-- 添加图片区域 -->
      <scroll-view scroll-x="true" class="img-list-box" show-scrollbar="false">
        <view class="img-list">
          <view class="img-item" v-for="(item,index) in data.imgList" :key="index">
            <view class="img-num">{{index+1}}</view>
            <view class="del-img" @click="delImgList(index)">×</view>
            <image class="pub-img" :src="item.url" mode="aspectFill"></image> 
          </view>
           <view class="img-item" v-for="(item,index) in data.uploadImgList" :key="index">
             <view class="img-num">{{data.imgList.length+index+1}}</view>
             <view class="del-img" @click="delUploadImg(index)">×</view>
             <image class="pub-img" :src="item" mode="aspectFill"></image> 
           </view>
          <view style="padding-right: 10px;">
            <view class="add-img" @click="addImg">
              <text>+</text>
            </view>
          </view>
        </view>
      </scroll-view>
      <!-- 标题区域 -->
      <view class="input-title">
        <input v-model="data.title" class="p-input" type="text" placeholder="标题内容(20)" maxlength="20"/>
      </view>
      <!-- 内容区域 -->
      <view class="content-view">
        <view class="content-box">
          <textarea class="content-textarea" v-model="data.content" @blur="bindTextAreaBlur" auto-height placeholder="填写内容..." maxlength="1000"/>
        </view>
      </view>
    
    <!-- 底部操作栏 -->
    <view class="pub-tool-box">
      <view class="draft-box" @click="saveDraft">
        <image class="draft-img" src="../../static/img/draft.png"></image>
        <text class="draft-text">存草稿</text>
      </view>
      <button class="p-button" @click="publishNote">发布笔记</button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs,onMounted } from 'vue';
import {onLoad,onUnload} from '@dcloudio/uni-app'
import helper from "../../common/helper.js"
 
const data = reactive({
  note:{},
  title:"",
  content:"",
  imgList:[],
  uploadImgList:[],
  noteId: "",
  msgType:"",
  messageText:"",
  deleteImgId:[],
  uploadImgId:[],
});

const message = ref(null)

function messageToggle(type,text) {
  data.msgType = type
  data.messageText = text
  message.value.open()
}

onLoad((options)=>{
  console.log(options)
  if(options.noteId != null){
    data.noteId = options.noteId
    console.log(data.noteId)
    getNote()
  }
})

async function getNote(){
  let res = await helper.getNoteDetailReq(data.noteId)
  if(res.data.code == 200){
    data.note = res.data.data
    data.note.time = helper.getDateTime(data.note.time)
    data.title = data.note.title
    data.content = data.note.content
    data.imgList = data.note.imageList
  }
}

function bindTextAreaBlur(e) {
  console.log(e.detail.value)
}

function saveDraft(){
  console.log("存入草稿")
}

async function publishNote(){
  console.log("发布笔记")
  if(data.uploadImgList.length == 0 && data.imgList.length == 0){
    messageToggle("info","请上传图片！")
    return
  }
  //检测是否存在空
  if(data.content.trim() != "" || data.title.trim() != ""){
    //发送请求
    //发布笔记
    if(data.noteId == ""){
      const result1 = await punlishReq()
      console.log(result1)
      if(result1.data.code == 200){
        for(let i = 0; i < data.uploadImgList.length; i++){
          const result2 = await uploadNoteImage(data.noteId,i)
          let res2 = JSON.parse(result2.data)
          console.log(res2)
          if(res2.code == 200){
            data.uploadImgId.push(res2.data)
          }else{
            messageToggle("info",res2.msg)
            if(data.uploadImgId.length > 0){
              deleteNoteImage(data.uploadImgId)
            }
            helper.deleteNoteReq(data.noteId)
            data.noteId = ""
            return
          }
        }
        uni.navigateBack()
      }else{
        messageToggle("info","发布失败!")
      }
    }else{
      //更新笔记
      for(let i = 0; i < data.uploadImgList.length; i++){
        const result1 = await uploadNoteImage(data.noteId,i)
        let res1 = JSON.parse(result1.data)
        console.log(res1)
        if(res1.code == 200){
          data.uploadImgId.push(res1.data)
        }else{
          messageToggle("info",res1.msg)
          if(data.uploadImgId.length > 0){
            deleteNoteImage(data.uploadImgId)
          }
          return
        }
      }
      let res = await updateNote()
      if(res.data.code == 200){
        uni.navigateBack()
      }else{
        messageToggle("info","发布失败!")
        if(data.uploadImgId.length > 0){
          deleteNoteImage(data.uploadImgId)
        }
      }
    }
  }
}

function punlishReq(){
  return new Promise((resolve, reject) => {
    uni.request({
          url: helper.webUrl+'/note/publishNote', 
          method:'POST',
          header: {
              'Content-Type': 'application/json' //自定义请求头信息
          },
          data: {
            noteId: data.noteId,
            userId: helper.getUserId(),
            title: data.title,
            content: data.content
          },
          success: (res) => {
            console.log(res.data);
            if(res.data.code == 200){
              data.noteId = res.data.data
              resolve(res)
            }else{
              messageToggle("info",res.data.msg)
            }
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
      });
  });   
}

function updateNote(){
  return new Promise((resolve, reject) => {
    uni.request({
          url: helper.webUrl+'/note/updateNote', 
          method:'POST',
          header: {
              'Content-Type': 'application/json' //自定义请求头信息
          },
          data: {
            noteId: data.noteId,
            title: data.title,
            content: data.content,
            noteImageIdList: data.deleteImgId
          },
          success: (res) => {
            console.log(res.data);
            resolve(res)
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
      });
  });   
}

function deleteNoteImage(idList){
  return new Promise((resolve, reject) => {
    uni.request({
          url: helper.webUrl+'/note/deleteNoteImage', 
          method:'POST',
          header: {
            'Content-Type': 'application/json' //自定义请求头信息,
          },
          data: {
            noteImageIdList: idList
          },
          success: (res) => {
            console.log(res.data);
            resolve(res)
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
      });
  });   
}

function uploadNoteImage(noteId,i){
  return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: helper.webUrl + '/note/uploadNoteImg',
        filePath: data.uploadImgList[i],
        name: 'file',
        formData:{
          'noteId': noteId,
          'imageIndex': data.imgList.length+i+1
        },
        success:(res) =>{
          resolve(res)
        },
        fail: (err) => {
          messageToggle("info","上传失败")
          console.error('上传失败:', err);
        },
        complete: (completeRes) => {
          console.log('上传完成, 状态:', completeRes.statusCode);
        }
      })
  });   
}

function delUploadImg(index){
  console.log("删除上传照片"+index)
  data.uploadImgList.splice(index,1)
}

function delImgList(index){
  console.log("删除原有照片"+index)
  data.deleteImgId.push(data.imgList[index].id)
  data.imgList.splice(index,1)
}

function addImg(){
  console.log("添加图片")
  uni.chooseImage({
  	count: 6, //默认9
  	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
  	sourceType: ['album'], //从相册选择
  	success: function (res) {
  		console.log(JSON.stringify(res));
      for(let i = 0; i < res.tempFilePaths.length; i++){
        data.uploadImgList.push(res.tempFilePaths[i])
      }
      console.log(data.uploadImgList)
  	}
  });
}

</script>

<style>
.publish-view{
  width: 100vw;
  height: 100vh;
  background-color: #f4f4f4;
}
.img-list-box{
  width: 100vw;
  height: 20vh;
  background-color: #fff;
  white-space: nowrap;
  border-bottom: 1px solid #c5c5c5;
}
.img-list{
  display: flex;
  padding: 15px;
}
.img-item{
  width: 100px;
  height: 100px;
  border-radius: 10px;
  margin: 5px;
}
.pub-img{
  width: 100px;
  height: 100px;
  border-radius: 10px;
}
.img-num{
  position: absolute;
  padding: 5px;
  background-color: red;
  border-bottom-right-radius: 10px;
  border-top-left-radius: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
}
.del-img{
  position: absolute;
  background-color: #89C0FF;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  color: #fff;
  display: flex;
  margin-left: 80px;
  justify-content: center;
}
.add-img{
  margin: 5px;
  width: 100px;
  height: 100px;
  border-radius: 10px;
  background-color: #EBEBEB;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  color: #949494;
}
.input-title{
  width: 100vw;
  height: 7vh;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-left: 20px;
  border-bottom: 1px solid #c5c5c5;
}
.p-input{
  font-size: 18px;
  width: 100%;
}
.content-view{
  width: 100vw;
  background-color: #fff;
}
.content-box{
  width: 95%;
  display: flex;
  margin: auto;
  padding-top: 8px;
}
.content-textarea{
  width: 100%;
  min-height: 50vh;
  font-size: 18px;
}
.pub-tool-box{
  position: absolute;
  bottom: 0;
  width: 100vw;
  height: 8vh;
  background-color: #fff;
  display: flex;
}
.draft-box{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-left: 30px;
}
.draft-img{
  width: 30px;
  height: 30px;
}
.p-button{
  width: 60%;
  background-color: #89C0FF;
  color: #fff;
  font-size: 16px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: auto;
}
</style>
